<template>
  <view class="profile-edit" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="编辑资料" 
      :showBack="true"
      :showRight="true"
      rightText="保存"
      @rightClick="handleSave"
    />
    
    <view class="edit-content">
      <!-- 头像编辑 -->
      <view class="avatar-section">
        <view class="section-title">头像</view>
        <view class="avatar-container" @click="chooseAvatar">
          <image 
            :src="formData.avatar || '/static/default-avatar.png'" 
            class="avatar-image"
            mode="aspectFill"
          />
          <view class="avatar-mask">
            <text class="iconfont icon-camera"></text>
            <text class="avatar-text">更换头像</text>
          </view>
        </view>
      </view>
      
      <!-- 基本信息编辑 -->
      <view class="form-section">
        <view class="form-item primary-field">
          <view class="item-label">
            <text>用户名</text>
            <text class="required-mark">*</text>
          </view>
          <input 
            v-model="formData.username"
            class="item-input"
            placeholder="请输入用户名"
            maxlength="20"
          />
        </view>
        
        <view class="form-item">
          <view class="item-label">邮箱</view>
          <input 
            v-model="formData.email"
            class="item-input"
            placeholder="请输入邮箱"
            type="email"
          />
        </view>
        
        <view class="form-item">
          <view class="item-label">手机号</view>
          <input 
            v-model="formData.phone"
            class="item-input"
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
          />
        </view>
        
        <view class="form-item form-item-textarea primary-field">
          <view class="item-label">
            <text>个人简介</text>
            <text class="recommended-mark">推荐</text>
          </view>
          <textarea 
            v-model="formData.bio"
            class="item-textarea"
            placeholder="介绍一下自己吧..."
            maxlength="200"
            auto-height
          />
          <view class="char-count">{{ formData.bio.length }}/200</view>
        </view>
      </view>
      
      <!-- 其他设置 -->
      <view class="settings-section">
        <view class="section-title">其他设置</view>
        
        <view class="setting-item" @click="showGenderPicker = true">
          <view class="setting-label">性别</view>
          <view class="setting-value">
            <text>{{ genderOptions.find(item => item.value === formData.gender)?.label || '未设置' }}</text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </view>
        
        <view class="setting-item" @click="showBirthdayPicker = true">
          <view class="setting-label">生日</view>
          <view class="setting-value">
            <text>{{ formData.birthday || '未设置' }}</text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </view>
        
        <view class="setting-item" @click="showLocationPicker = true">
          <view class="setting-label">所在地</view>
          <view class="setting-value">
            <text>{{ formData.location || '未设置' }}</text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 性别选择器 -->
    <picker 
      v-if="showGenderPicker"
      :range="genderOptions"
      range-key="label"
      @change="onGenderChange"
      @cancel="showGenderPicker = false"
    >
      <view></view>
    </picker>
    
    <!-- 生日选择器 -->
    <picker 
      v-if="showBirthdayPicker"
      mode="date"
      :value="formData.birthday"
      @change="onBirthdayChange"
      @cancel="showBirthdayPicker = false"
    >
      <view></view>
    </picker>
    
    <!-- 加载提示 -->
    <LoadingComponent v-if="loading" />
  </view>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { updateUserProfileAPI, uploadAvatarAPI } from '@/api/user'
import { extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'

export default {
  name: 'ProfileEdit',
  components: {
    CustomNavBar,
    LoadingComponent
  },
  setup() {
    const userStore = useUserStore()
    const loading = ref(false)
    const showGenderPicker = ref(false)
    const showBirthdayPicker = ref(false)
    const showLocationPicker = ref(false)
    
    const formData = reactive({
      username: '',
      email: '',
      phone: '',
      avatar: '',
      bio: '',
      gender: '',
      birthday: '',
      location: ''
    })
    
    const genderOptions = [
      { label: '男', value: 'male' },
      { label: '女', value: 'female' },
      { label: '保密', value: 'secret' }
    ]
    
    // 初始化表单数据
    const initFormData = () => {
      const userInfo = userStore.userInfo
      if (userInfo) {
        formData.username = userInfo.username || ''
        formData.email = userInfo.email || ''
        formData.phone = userInfo.phone || ''
        formData.avatar = userInfo.avatar || ''
        formData.bio = userInfo.bio || ''
        formData.gender = userInfo.gender || ''
        formData.birthday = userInfo.birthday || ''
        formData.location = userInfo.location || ''
      }
    }
    
    // 选择头像
    const chooseAvatar = () => {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          try {
            loading.value = true
            const filePath = res.tempFilePaths[0]
            const result = await uploadAvatarAPI(filePath)
            const uploadData = extractResponseData(result)
            formData.avatar = uploadData.url
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            })
          } catch (error) {
            console.error('头像上传失败:', error)
            uni.showToast({
              title: '头像上传失败',
              icon: 'none'
            })
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    // 性别选择
    const onGenderChange = (e) => {
      const index = e.detail.value
      formData.gender = genderOptions[index].value
      showGenderPicker.value = false
    }
    
    // 生日选择
    const onBirthdayChange = (e) => {
      formData.birthday = e.detail.value
      showBirthdayPicker.value = false
    }
    
    // 表单验证
    const validateForm = () => {
      if (!formData.username.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      
      if (formData.username.length < 2 || formData.username.length > 20) {
        uni.showToast({
          title: '用户名长度为2-20个字符',
          icon: 'none'
        })
        return false
      }
      
      if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        uni.showToast({
          title: '请输入正确的邮箱格式',
          icon: 'none'
        })
        return false
      }
      
      if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return false
      }
      
      return true
    }
    
    // 保存资料
    const handleSave = async () => {
      if (!validateForm()) return
      
      try {
        loading.value = true
        
        const updateData = {
          username: formData.username.trim(),
          email: formData.email.trim(),
          phone: formData.phone.trim(),
          avatar: formData.avatar,
          bio: formData.bio.trim(),
          gender: formData.gender,
          birthday: formData.birthday,
          location: formData.location
        }
        
        const result = await updateUserProfileAPI(updateData)
        const updatedUser = extractResponseData(result)
        
        // 更新本地用户信息
        userStore.setUserInfo({
          ...userStore.userInfo,
          ...updatedUser
        })
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      initFormData()
    })
    
    return {
      userStore,
      loading,
      formData,
      genderOptions,
      showGenderPicker,
      showBirthdayPicker,
      showLocationPicker,
      chooseAvatar,
      onGenderChange,
      onBirthdayChange,
      handleSave
    }
  },
  
  computed: {
    themeClass() {
      return this.userStore?.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-edit {
  min-height: 100vh;
  background: #f5f5f5;
}

.edit-content {
  padding: 20rpx;
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 20rpx);
  min-height: calc(100vh - calc(var(--status-bar-height, 44rpx) + 88rpx));
}

.avatar-section {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  text-align: center;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .avatar-container {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    margin: 0 auto;
    border-radius: 50%;
    overflow: hidden;
    
    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
    
    .avatar-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;
      
      .iconfont {
        color: white;
        font-size: 40rpx;
        margin-bottom: 8rpx;
      }
      
      .avatar-text {
        color: white;
        font-size: 24rpx;
      }
    }
    
    &:active .avatar-mask {
      opacity: 1;
    }
  }
}

.form-section {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.form-item {
  padding: 30rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.form-item-textarea {
    flex-direction: column;
    align-items: stretch;
    position: relative;
  }
  
  &.primary-field {
    background-color: #f6f8ff;
    border-left: 4rpx solid #1890ff;
  }
  
  .item-label {
    width: 140rpx;
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8rpx;
  }
  
  .required-mark {
    color: #ff4d4f;
    font-size: 24rpx;
    font-weight: bold;
  }
  
  .recommended-mark {
    background-color: #1890ff;
    color: #ffffff;
    font-size: 20rpx;
    padding: 2rpx 8rpx;
    border-radius: 8rpx;
    font-weight: normal;
  }
  
  .item-input {
    flex: 1;
    font-size: 32rpx;
    color: #333;
    text-align: right;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .item-textarea {
    width: 100%;
    font-size: 32rpx;
    color: #333;
    margin-top: 20rpx;
    min-height: 120rpx;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .char-count {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.settings-section {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  
  .section-title {
    padding: 30rpx 32rpx 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.setting-item {
  padding: 30rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background: #f8f8f8;
  }
  
  .setting-label {
    font-size: 32rpx;
    color: #333;
  }
  
  .setting-value {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 30rpx;
    
    .iconfont {
      margin-left: 12rpx;
      font-size: 24rpx;
      color: #ccc;
    }
  }
}

/* 主题适配 */
.theme-dark .form-item.primary-field {
  background-color: #2a2d32;
  border-left-color: #1890ff;
}

.theme-dark .item-label {
  color: #e8e8e8;
}

.theme-dark .required-mark {
  color: #ff7875;
}

.theme-dark .recommended-mark {
  background-color: #1890ff;
  color: #ffffff;
}
.theme-light.profile-edit {
  background: #f5f5f5 !important;
}

.theme-dark.profile-edit {
  background: #1e1e1e !important;
}

.theme-dark .avatar-section,
.theme-dark .form-section,
.theme-dark .settings-section {
  background: #252526 !important;
}

.theme-dark .form-item {
  border-bottom-color: #404040 !important;
}

.theme-dark .section-title {
  color: #e8e8e8 !important;
  border-bottom-color: #404040 !important;
}

.theme-dark .item-label,
.theme-dark .setting-label {
  color: #e8e8e8 !important;
}

.theme-dark .item-input,
.theme-dark .item-textarea {
  color: #e8e8e8 !important;
  background-color: transparent !important;
}

.theme-dark .item-input::placeholder,
.theme-dark .item-textarea::placeholder {
  color: #b3b3b3 !important;
}

.theme-dark .char-count {
  color: #b3b3b3 !important;
}

.theme-dark .setting-value {
  color: #b3b3b3 !important;
}

.theme-dark .setting-item:active {
  background: #2d2d30 !important;
}

.theme-dark .avatar-mask {
  background: rgba(0, 0, 0, 0.7) !important;
}
</style> 